package com.ic.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ic.domain.AppRules;
import com.ic.domain.Rule;
import com.ic.service.RuleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class RuleServiceImpl implements RuleService {
    private List<Rule> list = Collections.synchronizedList(Lists.newArrayList());

    private Map<String, AppRules> rulesMap = Maps.newConcurrentMap();

    @Override
    public AppRules getAppRules(String appId) {
        return rulesMap.get(appId);
    }

    @Override
    public void save(Rule rule) {
        rule.setVersion("V_" + System.currentTimeMillis());
        if (StringUtils.isBlank(rule.getId())) {
            rule.setId(UUID.randomUUID().toString());
            list.add(rule);
        } else {
            list.stream().filter(r -> r.getId().equals(rule.getId())).findAny().ifPresent(r -> {
                r.setVersion(rule.getVersion());
                r.setExpression(rule.getExpression());
            });
        }
        saveRuleMap(rule);
    }

    private void saveRuleMap(Rule rule) {
        AppRules appRules = getAppRules(rule.getAppId());
        if (null == appRules) {
            appRules = new AppRules();
            appRules.setRules(Lists.newArrayList(rule));
        } else {
            appRules.getRules().removeIf(r -> r.getId().equals(rule.getId()));
            appRules.getRules().add(rule);
        }
        appRules.setVersion("VA_" + System.currentTimeMillis());
        rulesMap.put(rule.getAppId(), appRules);
    }

    @Override
    public void delete(String id) {
        Rule rule = list.stream().filter(r -> r.getId().equals(id)).findAny()
                .orElse(null);
        if (null == rule) return;
        list.remove(rule);
        deleteFromRuleMap(rule);
    }

    @Override
    public List<Rule> list() {
        return list;
    }

    private void deleteFromRuleMap(Rule rule) {
        AppRules appRules = getAppRules(rule.getAppId());
        if (null != appRules) {
            appRules.getRules().removeIf(r -> r.getId().equals(rule.getId()));
            appRules.setVersion("VA_" + System.currentTimeMillis());
            rulesMap.put(rule.getAppId(), appRules);
        }
    }
}
